<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Minio测试前端直传</title>
    <script src="js/vue.js"></script>
    <script src="js/jquery.js"></script>
</head>
<body>
<div id="app">
    <label>
        Object Key:
        <input id="file" type="text" v-model="objectKey" placeholder="请输入Object Key">
    </label>
    <button @click="downloadFile" :disabled="!objectKey">下载文件</button>
    <p v-if="downloadStatus">{{ downloadStatus }}</p>
</div>

<script>
    var vm = new Vue({
        el: "#app",
        data() {
            return {
                objectKey: "",
                downloadStatus: ""
            };
        },
        methods: {
            /**
             * 下载文件
             */
            async downloadFile() {
                if (!this.objectKey) {
                    alert('请输入Object Key');
                    return;
                }

                this.downloadStatus = "正在下载...";
                try {
                    const response = await this.fetchFile();
                    const blob = await response;
                    const filename = this.objectKey;

                    // 创建一个临时的 <a> 元素
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob); // 创建对象URL
                    link.download = filename; // 设置下载的文件名
                    document.body.appendChild(link);
                    link.click(); // 触发下载
                    document.body.removeChild(link); // 移除临时元素
                    URL.revokeObjectURL(link.href); // 释放对象URL

                    this.downloadStatus = "下载成功";
                } catch (error) {
                    console.error('下载失败:', error);
                    this.downloadStatus = "下载失败，请重试";
                    alert('文件下载失败，请重试');
                }
            },
            /**
             * 发起文件下载请求
             */
            fetchFile() {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: `http://localhost:9989/oss/download?bucketName=demo&fileName=${this.objectKey}`,
                        method: "POST", // 使用GET方法来下载文件
                        xhrFields: {
                            responseType: 'blob' // 确保响应类型为blob
                        },
                        headers: {
                            'Accept': 'application/octet-stream' // 设置接受的内容类型
                        },
                        success: (blob, status, xhr) => {
                            resolve(blob, status, xhr)
                        },
                        error: reject
                    });
                });
            },
        }
    });
</script>
</body>
</html>